package com.ruoyi.base.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.ruoyi.base.domain.BaseStandardTenderSheet;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.domain.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.common.utils.TreeBuildUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import com.ruoyi.base.domain.bo.BaseStandardSheetBo;
import com.ruoyi.base.domain.vo.BaseStandardSheetVo;
import com.ruoyi.base.domain.BaseStandardSheet;
import com.ruoyi.base.mapper.BaseStandardSheetMapper;
import com.ruoyi.base.service.IBaseStandardSheetService;

import java.util.List;
import java.util.Map;
import java.util.Collection;
import java.util.stream.Collectors;

/**
 * 标准投标清单Service业务层处理
 *
 * @author zyb
 * @date 2024-09-29
 */
@RequiredArgsConstructor
@Service
public class BaseStandardSheetServiceImpl implements IBaseStandardSheetService {

    private final BaseStandardSheetMapper baseMapper;

    /**
     * 查询标准投标清单
     */
    @Override
    public BaseStandardSheetVo queryById(Long sheetId){
        return baseMapper.selectVoById(sheetId);
    }

    /**
     * 查询标准投标清单列表
     */
    @Override
    public TableDataInfo<BaseStandardSheetVo> queryPageList(BaseStandardSheetBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<BaseStandardSheet> lqw = buildQueryWrapper(bo);
        Page<BaseStandardSheetVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询标准投标清单列表
     */
    @Override
    public List<BaseStandardSheetVo> queryList(BaseStandardSheetBo bo) {
        LambdaQueryWrapper<BaseStandardSheet> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<BaseStandardSheet> buildQueryWrapper(BaseStandardSheetBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<BaseStandardSheet> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getParentId() != null, BaseStandardSheet::getParentId, bo.getParentId());
        lqw.eq(bo.getSort() != null, BaseStandardSheet::getSort, bo.getSort());
        lqw.eq(StringUtils.isNotBlank(bo.getSheetCode()), BaseStandardSheet::getSheetCode, bo.getSheetCode());
        lqw.like(StringUtils.isNotBlank(bo.getSheetName()), BaseStandardSheet::getSheetName, bo.getSheetName()).or()
        .like(StringUtils.isNotBlank(bo.getSheetName()), BaseStandardSheet::getSpecificationName, bo.getSheetName());
        lqw.eq(StringUtils.isNotBlank(bo.getSheetLevel()), BaseStandardSheet::getSheetLevel, bo.getSheetLevel());
        lqw.eq(StringUtils.isNotBlank(bo.getSheetUnit()), BaseStandardSheet::getSheetUnit, bo.getSheetUnit());
        lqw.eq(bo.getSheetTaxRate() != null, BaseStandardSheet::getSheetTaxRate, bo.getSheetTaxRate());
        lqw.eq(StringUtils.isNotBlank(bo.getLowerFlag()), BaseStandardSheet::getLowerFlag, bo.getLowerFlag());
        lqw.orderByAsc(BaseStandardSheet::getSheetCode);
        return lqw;
    }

    /**
     * 新增标准投标清单
     */
    @Override
    public Boolean insertByBo(BaseStandardSheetBo bo) {
        BaseStandardSheet add = BeanUtil.toBean(bo, BaseStandardSheet.class);

        //是否存在父类
        List<BaseStandardSheet> baseStandardSheetList = baseMapper.selectList(new LambdaQueryWrapper<BaseStandardSheet>()
            .eq(bo.getParentId() != null, BaseStandardSheet::getSheetId, bo.getParentId()));
        //获取同等级编号最大值 一二级查询
        List<BaseStandardSheet> baseStandardSheets = baseMapper.selectList(new LambdaQueryWrapper<BaseStandardSheet>()
            .eq(StringUtils.isNotBlank(bo.getSheetLevel()), BaseStandardSheet::getSheetLevel, bo.getSheetLevel())
            .eq(bo.getParentId() != null, BaseStandardSheet::getParentId, bo.getParentId())
            .orderByDesc(BaseStandardSheet :: getSheetCode).last("limit 1"));
        //获取同等级编号最大值 三级查询
        List<BaseStandardSheet> baseStandardSheets1 = baseMapper.selectList(new LambdaQueryWrapper<BaseStandardSheet>()
            .eq(StringUtils.isNotBlank(bo.getSheetLevel()), BaseStandardSheet::getSheetLevel, bo.getSheetLevel())
            .eq(bo.getParentId() != null, BaseStandardSheet::getParentId, bo.getParentId())
            .orderByDesc(BaseStandardSheet :: getSpecificationCode).last("limit 1"));
        if (CollectionUtils.isNotEmpty(baseStandardSheetList)){
            //二级
            if ("2".equals(add.getSheetLevel())){
                if (CollectionUtils.isNotEmpty(baseStandardSheets)) {
                    String str = baseStandardSheets.get(0).getSheetCode();
                    String substring = str.substring(str.length() - 3);
                    int initialValue = Integer.parseInt(substring);
                    int newValue = initialValue + 1;
                    StringBuilder sb = new StringBuilder();
                    sb.append(String.format("%03d", newValue));
                    add.setSheetCode(baseStandardSheetList.get(0).getSheetCode()+String.valueOf(sb));
                }else {
                    add.setSheetCode(baseStandardSheetList.get(0).getSheetCode()+"001");
                }
            }
            //三级
            if ("3".equals(add.getSheetLevel())){
                if (CollectionUtils.isNotEmpty(baseStandardSheets1)) {
                    String str = baseStandardSheets1.get(0).getSpecificationCode();
                    String substring = str.substring(str.length() - 3);
                    int initialValue = Integer.parseInt(substring);
                    int newValue = initialValue + 1;
                    StringBuilder sb = new StringBuilder();
                    sb.append(String.format("%03d", newValue));
                    add.setSheetCode(baseStandardSheetList.get(0).getSheetCode());
                    add.setSheetName(baseStandardSheetList.get(0).getSheetName());
                    add.setSpecificationCode(baseStandardSheetList.get(0).getSheetCode() + String.valueOf(sb));
                    add.setSpecificationName(bo.getSheetName());
                }else {
                    add.setSheetCode(baseStandardSheetList.get(0).getSheetCode());
                    add.setSheetName(baseStandardSheetList.get(0).getSheetName());
                    add.setSpecificationCode(baseStandardSheetList.get(0).getSheetCode()+"001");
                    add.setSpecificationName(bo.getSheetName());
                }
            }
        }else {
            //一级
            if (CollectionUtils.isNotEmpty(baseStandardSheets)){
                String str = baseStandardSheets.get(0).getSheetCode();
                int initialValue = Integer.parseInt(str);
                int newValue = initialValue + 1;
                StringBuilder sb = new StringBuilder();
                sb.append(String.format("%03d", newValue));
                add.setSheetCode(String.valueOf(sb));
            }else {
                add.setSheetCode("001");
            }
        }

        //默认序号
        List<BaseStandardSheet> baseStandardSheets2 = baseMapper.selectList(new LambdaQueryWrapper<BaseStandardSheet>()
            .eq(StringUtils.isNotBlank(bo.getSheetLevel()), BaseStandardSheet::getSheetLevel, bo.getSheetLevel())
            .eq(bo.getParentId() != null, BaseStandardSheet::getParentId, bo.getParentId())
            .orderByDesc(BaseStandardSheet :: getSort).last("limit 1"));
        if(CollectionUtils.isNotEmpty(baseStandardSheets2)){
            add.setSort(baseStandardSheets2.get(0).getSort()+1);
        }else {
            add.setSort(1L);
        }
        validEntityBeforeSave(add);

        //修改父类LowerFlag
        if (CollectionUtils.isNotEmpty(baseStandardSheetList)){
            BaseStandardSheet baseStandardSheet = baseStandardSheetList.get(0);
            if ("0".equals(baseStandardSheet.getLowerFlag())){
                baseStandardSheet.setLowerFlag("1");
                baseMapper.updateById(baseStandardSheet);
            }
        }

        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setSheetId(add.getSheetId());
        }
        return flag;
    }

    /**
     * 修改标准投标清单
     */
    @Override
    public Boolean updateByBo(BaseStandardSheetBo bo) {
        BaseStandardSheet update = BeanUtil.toBean(bo, BaseStandardSheet.class);
        update.setSpecificationName(update.getSheetName());
        update.setSheetName(null);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(BaseStandardSheet entity){
        //TODO 做一些数据校验,如唯一约束
        boolean exists = baseMapper.exists(new LambdaQueryWrapper<BaseStandardSheet>()
            .ne(ObjUtil.isNotNull(entity.getSheetId()), BaseStandardSheet::getSheetId, entity.getSheetId())
            .eq(BaseStandardSheet::getParentId, entity.getParentId())
            .eq(BaseStandardSheet::getSheetName, entity.getSheetName())
            .eq(BaseStandardSheet::getSpecificationName, entity.getSpecificationName()));
        if (exists) {
            throw new ServiceException("新增清单'" + entity.getSheetName()+entity.getSpecificationName()+ "'失败，清单名称已存在");
        }
    }

    /**
     * 批量删除标准投标清单
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
            ids.forEach(t->{

                BaseStandardSheetVo baseStandardSheetVo = baseMapper.selectVoById(t);
                if (ObjectUtils.isNotEmpty(baseStandardSheetVo)){
                    //是否存在同父类的
                    List<BaseStandardSheet> baseStandardSheetList = baseMapper.selectList(new LambdaQueryWrapper<BaseStandardSheet>()
                        .ne(baseStandardSheetVo.getSheetId() != null, BaseStandardSheet::getSheetId,baseStandardSheetVo.getSheetId())
                        .eq(baseStandardSheetVo.getParentId() != null, BaseStandardSheet::getParentId, baseStandardSheetVo.getParentId()));
                    if (CollectionUtils.isEmpty(baseStandardSheetList)){
                        //如果为空则修改父类的状态
                        BaseStandardSheet selectOne = baseMapper.selectOne(new LambdaQueryWrapper<BaseStandardSheet>()
                            .eq(baseStandardSheetVo.getParentId() != null, BaseStandardSheet::getSheetId, baseStandardSheetVo.getParentId()));
                        if (ObjectUtils.isNotEmpty(selectOne)){
                            selectOne.setLowerFlag("0");
                            baseMapper.updateById(selectOne);
                        }
                    }
                }
            });
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public List<Tree<Long>> selectstandardSheetTreeList(BaseStandardSheetBo bo) {
        List<BaseStandardSheetVo> baseStandardSheetVoList = this.queryList(bo);
        baseStandardSheetVoList.forEach(t->{
            if ("3".equals(t.getSheetLevel())){
                t.setSheetCode(t.getSpecificationCode());
                t.setSheetName(t.getSpecificationName());
            }
        });
        return TreeSelect(baseStandardSheetVoList);
    }

    private List<Tree<Long>> TreeSelect(List<BaseStandardSheetVo> list) {
        if (CollUtil.isEmpty(list)) {
            return CollUtil.newArrayList();
        }
        List<Tree<Long>> build = TreeBuildUtils.build(list, (sheetVo, tree) -> {
                tree.setId(sheetVo.getSheetId());
                tree.setParentId(sheetVo.getParentId());
                tree.setName(sheetVo.getSheetName());
                tree.setWeight(sheetVo.getSort());
                tree.putExtra("sheetLevel", sheetVo.getSheetLevel());
                tree.putExtra("sheetCode", sheetVo.getSheetCode());
                tree.putExtra("sheetUnit", sheetVo.getSheetUnit());
                tree.putExtra("sheetTaxRate", sheetVo.getSheetTaxRate());
                tree.putExtra("lowerFlag", sheetVo.getLowerFlag());
                tree.putExtra("remark", sheetVo.getRemark());
            });
        return build;
    }
}
